package com.slink.xin.framework.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

import com.slink.xin.common.domain.bo.CookieUser;

public class CookieUtil {
	public static final String cookieDomainName = "mem_cookie_info";

	public static final String webKey = "fxfk";
	// 设置cookie有效期是2个星期
	public static final long cookieMaxAge = 3600 * 24 * 14;

	public static void saveCookie(CookieUser user, HttpServletResponse response) {
		long validTime = System.currentTimeMillis() + (cookieMaxAge * 1000);
		String pwdMd5 = DigestUtils.md5Hex(user.getPassWord());
		if (pwdMd5.length() > 20) {
			pwdMd5 = pwdMd5.substring(0, 20);
		}
		String cookieValueWithMd5 = getMD5(user.getUserEmail() + "_" + pwdMd5
				+ "_" + validTime + "_" + webKey);
		String cookieValue = user.getUserEmail() + "_" + validTime + "_"
				+ cookieValueWithMd5;
		String cookieValueBase64 = new String(Base64.encodeBase64(cookieValue
				.getBytes()));
		Cookie cookie = new Cookie(cookieDomainName, cookieValueBase64);
		// 这个值应该大于或等于validTime
		cookie.setMaxAge(3600 * 24 * 16);

		cookie.setPath("/");
		response.addCookie(cookie);
	}

	/**
	 * 更新Cookie
	 * 
	 * @param request
	 * @param response
	 * @param cookieName
	 * @param cookieValue
	 *            cookieValue如果为null，表示清除cookie
	 */
	public static void updateCookie(HttpServletRequest request,
			HttpServletResponse response, String cookieName, String cookieValue) {
		Cookie cookie = new Cookie(cookieName, cookieValue);
		// cookie.setMaxAge(60 * 60 * 24 * 365);
		if (null == cookieValue) {
			cookie.setMaxAge(0);
		}
		cookie.setPath("/");

		Cookie[] cookies = request.getCookies();
		int i = 0;
		for (; i < cookies.length; i++) {
			if (null != cookieName
					&& cookies[i].getName().equalsIgnoreCase(cookieName)) {
				cookie = cookies[i];
				cookie.setValue(cookieValue);
				// cookie.setMaxAge(60 * 60 * 24 * 365);
				if (null == cookieValue) {
					cookie.setMaxAge(0);
				}
				cookie.setPath("/");
				break;
			}
		}
		response.addCookie(cookie);
	}

	public static void clearCookie(HttpServletResponse response) {
		Cookie cookie = new Cookie(cookieDomainName, null);
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	public static String getMD5(String value) {
		String result = null;
		try {
			byte[] valueByte = value.getBytes();
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(valueByte);
			result = toHex(md.digest());
		} catch (NoSuchAlgorithmException e2) {
			e2.printStackTrace();
		}
		return result;
	}

	private static String toHex(byte[] buffer) {
		StringBuffer sb = new StringBuffer(buffer.length * 2);
		for (int i = 0; i < buffer.length; i++) {
			sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
			sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
		}
		return sb.toString();
	}
}
